﻿using System.Linq;
using System;
using UtfprLibrary.Exceptions;

namespace UtfprLibrary.Helpers {
    /// <summary>
    /// A static helper class for reflection.
    /// </summary>
    public static class LinqHelper {
        /// <summary>
        /// Invoke the ToList() method of LINQ.
        /// </summary>
        /// <param name="collection">A collection</param>
        /// <returns>A list of objects with the collection type.</returns>
        /// <exception cref="UtfprLibrary.Exceptions.UtfprHelpersException">Thrown when an exception occurs.</exception>
        public static object InvokeToList(object collection) {
            try {
                var genericArgumentType = collection.GetType().GetGenericArguments().FirstOrDefault();

                var toListMethod = typeof(Enumerable)
                    .GetMethod("ToList")
                    .MakeGenericMethod(genericArgumentType);

                return toListMethod.Invoke(null, new object[] { collection });
            } catch (Exception ex) {
                throw new UtfprHelpersException(Properties.Resources.Helpers_LinqHelper_ExMsg_InvokeToList, ex);
            }
        }

        /// <summary>
        /// Invoke the Add(object item) method of LINQ.
        /// </summary>
        /// <param name="collection">A collection</param>
        /// <param name="item">The object to be added in the collection.</param>
        /// <exception cref="UtfprLibrary.Exceptions.UtfprHelpersException">Thrown when an exception occurs.</exception>
        public static void InvokeAdd(object collection, object item) {
            try {
                collection.GetType().GetMethod("Add")
                    .Invoke(collection, new object[] { item });
            } catch (Exception ex) {
                throw new UtfprHelpersException(Properties.Resources.Helpers_LinqHelper_ExMsg_InvokeAdd, ex);
            }
        }
    }
}